using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using App.Modelo.Interfaces;

namespace App.Git.Vista.Widgets
{
    public partial class ListadoBusquedaGenerico : Form
    {
        public IContenedorModulo ContenedorModulo { get; set; }
        public event EventHandler PerformSearch;
        public event EventHandler<ListadoBusquedaItemEventArgs> ItemSelected;
        public event EventHandler Cancelar;
        public event EventHandler<ListadoBusquedaSelectionChange> SelectionChange;

        private object itemSeleccionado;
        public object ItemSeleccionado
        {
            get { return itemSeleccionado; }
            set
            {
                ListadoBusquedaSelectionChange args = new ListadoBusquedaSelectionChange();
                args.OldValue = itemSeleccionado;
                itemSeleccionado = value;
                if (SelectionChange != null)
                    SelectionChange(this, args);
            }
        }

        public T GetSelectedItem<T>()
        {
            return (T) ItemSeleccionado;
        }

        public T BuscarElemento<T>()
        {
            DialogResult = DialogResult.None;
            ShowDialog();
            return GetSelectedItem<T>();
        }

        public void BuscarElemento()
        {
            DialogResult = DialogResult.None;
            if(null != ContenedorModulo)
                ContenedorModulo.AbrirFormulario(this);
            else
                Show();
        }

        
        public Control.ControlCollection ControlesGestion { get { return flowLayoutPanel1.Controls; } }


        public Boolean BotonSeleccionar
        {
            get { return toolStripButton1.Visible; }
            set { toolStripButton1.Visible = value; }
        }

        public Boolean BotonCancelar
        {
            get { return btnSeleccionar.Visible; }
            set { btnSeleccionar.Visible = value; }
        }

        private DataGridViewRow rowSelected;

        public DataGridViewRow RowSelected
        {
            get { return rowSelected; }
        }


        public ToolStripItemCollection Controles
        {
            get { return _tool.Items; }
        }

        private string _descripcionBusqueda;
        public String DescripcionBusqueda
        {
            get { return _descripcionBusqueda; }
            set { _descripcionBusqueda  = value; }
        }

        public Control.ControlCollection SearchControls
        {
            get { return _searchFieldsLayout.Controls; }
        }

        public DataGridViewColumnCollection Columns
        {
            get { return GridView.Columns; }
        }

        protected string SinResultados = "No se encontraron registros";


        public object DataSource
        {
            set
            {
                StatusNoRecords.Text = lblTotal.Text = "";
                GridView.DataSource = value;
                if( value is IList)
                {
                    var lista = (IList) value;
                    
                    lblTotal.Text = "Registros encontrados: " + lista.Count.ToString();
                    StatusNoRecords.Visible = lista.Count == 0;
                    lblTotal.Visible = !StatusNoRecords.Visible;
                    StatusNoRecords.Text = SinResultados;
                    
                    
                }
            }
            get { return GridView.DataSource; }
        }

        public DataGridViewRow FindRow(object DataObject)
        {
            for (var i = 0; i < GridView.Rows.Count; i++)
            {
                if (GridView.Rows[i].DataBoundItem == DataObject)
                    return GridView.Rows[i];
            }
            return null;
        }

        protected void MarcarFilaAsignada(DataGridViewRow row)
        {
            if (null != row)
            {
                DataGridViewCellStyle style = new DataGridViewCellStyle();

                style.Font = new Font(this.Font, FontStyle.Strikeout);
                style.BackColor = Color.Green;
                row.DefaultCellStyle = style;
            }
        }



        public ListadoBusquedaGenerico()
        {
            InitializeComponent();

            GridView.AutoGenerateColumns = false;
        
        }

      
        
        protected virtual void OnSearch()
        {

        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            OnSearch();

            if (PerformSearch != null)
                PerformSearch(this, new EventArgs());

        }

        private void ListadoBusquedaGenerico_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                case Keys.F3:
                    btnBuscar_Click(sender, e);
                    break;

            }
        }

        private void btnSeleccionar_Click(object sender, EventArgs e)
        {
            if (GridView.SelectedRows.Count == 1)
            {
                ListadoBusquedaItemEventArgs ea = new ListadoBusquedaItemEventArgs();
                ItemSeleccionado = ea.ItemSeleccionado = GridView.SelectedRows[0].DataBoundItem;
                DialogResult = DialogResult.OK;
                OnSelection();
                if (ItemSelected != null)
                    ItemSelected(this, ea);
                Close();
            }
            else
            {
                MessageBox.Show(
                    "Debe seleccionar al menos un registro",
                    this.Text,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation
                    );
            }
        }

        private void btnSeleccionar_Click(object sender, DataGridViewCellEventArgs e)
        {
            if( BotonSeleccionar )
            {
                btnSeleccionar_Click(sender, (EventArgs)e);    
            }
            
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

            DialogResult = DialogResult.Cancel;
            ItemSeleccionado = null;
            OnCancel();
            
            if (Cancelar != null)
                Cancelar(this, new EventArgs());
            Close();
        }

        public DataGridViewColumn AddColumn(string Text, string Property, int Width)
        {
            DataGridViewColumn col = AddColumn(Text, Property);
            col.Width = Width;
            col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            return col;
        }

        

        public DataGridViewColumn AddColumn(string text, string property)
        {
            DataGridViewColumn col = new DataGridViewTextBoxColumn()
            {
                HeaderText = text,
                DataPropertyName = property,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            };
            GridView.Columns.Add(col);
            return col;
        }
        public DataGridViewColumn AddColumn(string property)
        {
            return AddColumn(property, property);
        }
        // no se usa
        protected DataGridViewColumn FormatoColumna(DataGridViewColumn col, ListadoFormatoCell formato)
        {

            var cellStyle =col.CellTemplate.Style;
            switch (formato)
            {
                case ListadoFormatoCell.Numero:
                    cellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                    break;
                case ListadoFormatoCell.Moneda:
                    cellStyle.Format = "####,###.00";
                    cellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                    break;
                case ListadoFormatoCell.Id:
                    cellStyle.Format = "000000";
                    cellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                    break;
                case ListadoFormatoCell.FechaCorta:
                    cellStyle.Format = "d";
                    break;
                case ListadoFormatoCell.Numeracion:
                    cellStyle.Format = "0000-00000000";
                    cellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
                    break;
                case ListadoFormatoCell.Texto:
                default:
                    break;
            }
            
            return col;   
        }

        protected void EstablecerAnchos(params int[] widths)
        {
            for (int i = 0; i < Math.Min(widths.Length, GridView.Columns.Count); i++)
                GridView.Columns[i].Width = widths[i];
        }

        private void _grid_SelectionChanged(object sender, EventArgs e)
        {
            if (GridView.SelectedRows.Count == 1)
            {
                rowSelected = GridView.SelectedRows[0];
                ItemSeleccionado = rowSelected.DataBoundItem;
            }
            else
            {
                ItemSeleccionado = null;
                rowSelected = null;
            }
        }

        protected virtual void OnCancel()
        {
        }

        protected virtual void OnSelection()
        {
        }

        private void ListadoBusquedaGenerico_Load(object sender, EventArgs e)
        {
            flowLayoutPanel1.Visible = flowLayoutPanel1.Controls.Count > 0;
        }

        private void flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e)
        {
            flowLayoutPanel1.Visible = flowLayoutPanel1.Controls.Count > 0;
        }


        protected bool _seleccionar()
        {
            if( ItemSeleccionado != null )
                return true;
            MessageBox.Show("Debe seleccionar un elemento");
            return false;
        }

        protected bool _confirmar()
        {
            return _seleccionar() &&
                   MessageBox.Show("Esta seguro que desea borrar", Text, MessageBoxButtons.YesNo,
                                   MessageBoxIcon.Question) == DialogResult.Yes;
        }

    }
}